// menu
import $Request from '@/api'

let state = {
    loadMenuRouters: null,
    tagViewList: [],
    currentTagViews: null,
}

let getters = {
    getTagViewList(state) {
        return state.tagViewList
    },
    getMenuRoutes(state) {
        return state.loadMenuRouters
    },
    getCurrentTagView(state) {
        return state.currentTagViews
    },
}

let mutations = {
    SET_ROUTERS(state, payload) {
        state.loadMenuRouters = payload
    },
    SET_TAG_VIEW_ROUTES(state, payload) {
        let { path } = payload
        let pathArr = state.tagViewList.map(item => item.path)
        if (!pathArr.includes(path)) {
            state.tagViewList.push(payload)
        }
    },
    SET_CURRENT_TAG_VIEWS(state, payload) {
        state.currentTagViews = payload
    },
}

let actions = {
    delTabsView({ state }, payload) {
        state.tagViewList = state.tagViewList.filter(item => item.path !== payload.path)
    },
    dropTabsViewPages({ state }, payload) {
        state.tagViewList = state.tagViewList.filter(item => item.name !== payload)
    },
    loadMenuRouters({ commit }) {
        return new Promise((resolve, reject) => {
            $Request.commonApi.fetchUserInfo().then(resp => {
                if (resp) {
                    commit('SET_ROUTERS', resp)
                    resolve(resp)
                } else {
                    reject('error')
                }
            })
        })
    },
    setTabsName({ state }, payload) {
        state.tagViewList.forEach(item => {
            if (item.isSelected) {
                item.meta.title = payload
            }
        })
    },
}

export default {
    namespaced: true,
    state: state,
    getters: getters,
    mutations: mutations,
    actions: actions,
}
